package com.yeshine.opendata.api;

import com.yeshine.opendata.core.AppException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by taohj on 2014/9/23.
 */
@Controller
public class APIController {


    @Autowired
    API api;


    @RequestMapping(value = "api", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String api(HttpServletRequest request, @RequestParam("action") String action) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        api.setRequest(request);

        Class clazz = API.class;

        Method[] methods = clazz.getDeclaredMethods();

        Method method = null;
        for (Method m : methods) {
            if (m.getName().equals(action)) {
                method = m;
                break;
            }
        }
        if (method == null) {
            Result result = new Result();
            result.setMessage("该action值:" + action + ",不存在");
            result.setStatus(1);
            return result.toString();
        }


        try {
            Object object = method.invoke(api);
            return object.toString();
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof AppException) {
                AppException appException = (AppException) e.getTargetException();
                return appException.toString();
            }else{
                throw  e;
            }

        }

    }
}
